﻿using Xejen.Communication.Configuration;
using Xejen.Hosting;
using Xejen.Hosting.Extensions;
using Xejen.Logger;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;

namespace Xejen.Communication
{
    /// <summary>
    /// 通讯构建器的基类
    /// </summary>
    /// <typeparam name="TCommunicatorBuilder"><inheritdoc cref="ICommunicatorBuilder{TCommunicatorBuilder}" path="/summary"/></typeparam>
    /// <creator>marc</creator>
    public abstract class CommunicatorBuilder<TCommunicatorBuilder> : ICommunicatorBuilder<TCommunicatorBuilder>
          where TCommunicatorBuilder : class, ICommunicatorBuilder<TCommunicatorBuilder>
    {
        private readonly IAppHost _host;
        private readonly ILogger _logger;
        private readonly IConfiguration _configuration;
        private readonly ILoggerManager _loggerManager;

        /// <inheritdoc/>
        public IAppHost Host => _host;
        /// <summary>
        /// 配置
        /// </summary>
        protected IConfiguration Configuration => _configuration;
        /// <inheritdoc/>
        public ILoggerManager LoggerManager => _loggerManager;

        /// <inheritdoc cref="CommunicatorBuilder{TCommunicatorBuilder}"/>
        /// <param name="host"><inheritdoc cref="IAppHost" path="/summary"/></param>
        protected CommunicatorBuilder(IAppHost host)
        {
            Check.NotNull(host, nameof(host));

            _host = host;
            _configuration = host.Configuration;
            _loggerManager = host.LoggerManager;
            _logger = _loggerManager.CreateLogger<CommunicatorBuilder<TCommunicatorBuilder>>();
        }

        /// <inheritdoc/>
        protected TCommunicatorBuilder ConfigureServices(Action<IServiceCollection> configure)
        {
            _host.AddServices((services) =>
            {
                configure?.Invoke(services);
            });

            return this as TCommunicatorBuilder;
        }
    }
}
